﻿using B.S.Medical.Api.Read.Application.Command.Department;
using B.S.Medical.Api.Read.DTOS;
using B.S.Medical.Domain.Department;
using B.S.Medical.ErrorCode;
using B.S.Medical.Infrastructure.Interface;
using MediatR;

namespace B.S.Medical.Api.Read.Application.Handler.Department
{
    public class DepartmentTreeCommandHandle : IRequestHandler<DepartmentTreeCommand, ApiResult<List<DepartmentTreeDTO>>>
    {
        private readonly IBaseRepository<ManageModel> _manageRepository;
        public DepartmentTreeCommandHandle(IBaseRepository<ManageModel> manageRepository)
        {
            _manageRepository = manageRepository;
        }

        public async Task<ApiResult<List<DepartmentTreeDTO>>> Handle(DepartmentTreeCommand request, CancellationToken cancellationToken)
        {
            var allDepartments = _manageRepository.GetAll().Where(x => x.IsDeleted == false).ToList();
            var nodes = allDepartments.Select(d => new DepartmentTreeDTO
            {
                Id = d.Id,
                DepartmentName = d.DepartmentName,
                Children = new List<DepartmentTreeDTO>()
            }).ToList();

            // 建立Id到节点的映射
            var nodeDict = nodes.ToDictionary(n => n.Id);
            List<DepartmentTreeDTO> roots = new List<DepartmentTreeDTO>();
            foreach (var dept in allDepartments)
            {
                if (dept.ParetId == 0)
                {
                    roots.Add(nodeDict[dept.Id]);
                }
                else if (nodeDict.ContainsKey(dept.ParetId))
                {
                    nodeDict[dept.ParetId].Children.Add(nodeDict[dept.Id]);
                }
            }

            var result = new ApiResult<List<DepartmentTreeDTO>>
            {
                Code = ApiEnum.Success,
                Msg = "查询成功!",
                Data = roots
            };
            return await Task.FromResult(result);
        }
    }
}
